package com.plian.system.controller.fr.audit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.Func;
import com.plian.Tools.StringPool;
import com.plian.Tools.StringUtil;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.MyCustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.entity.fr.audit.AuditOrganizations;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.fr.audit.IAuditOrganizationsService;
import com.plian.system.vo.fr.audit.AuditOrganizationsVO;
import com.plian.system.wrapper.fr.audit.AuditOrganizationsWrapper;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Optional;

/**
 * 内部机构管理 控制器
 *
 * @author gangan
 * @since 2019-10-09
 */
@Slf4j
@RestController
@RequestMapping("api/auditorganizations")
@AllArgsConstructor
public class AuditOrganizationsController extends BaseController {

    private final IAuditOrganizationsService auditOrganizationsService;

    private final AuditOrganizationsWrapper auditOrganizationsWrapper;


    /**
     * 详情
     */
    @PostMapping("/detail")
    public R<AuditOrganizationsVO> detail(@Valid @RequestBody AuditOrganizations auditOrganizations) {
        AuditOrganizations detail = auditOrganizationsService.getOne(Condition.getQueryWrapper(auditOrganizations));
        return R.data(auditOrganizationsWrapper.entityToVO(detail));
    }

    /**
     * 分页 内部机构管理
     */
    @PostMapping("/list")
    public ListResult<AuditOrganizationsVO> list(@Valid @RequestBody Query query) {
        List<SearchEntity> entityList = query.getSearch();

		if (query.getAscs()==null&&query.getDescs()==null){
            query.setDescs("create_time");
		}
        QueryWrapper<AuditOrganizations> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new AuditOrganizations()), entityList
        );
        TokenSearch<AuditOrganizations> tokenSearch = new TokenSearch<>();
		tokenSearch.addTokenQuery(queryWrapper, query);

		IPage<AuditOrganizations> pages = auditOrganizationsService.page(Condition.getPage(query), queryWrapper);
        List<AuditOrganizationsVO> auditOrganizationsVOS = auditOrganizationsWrapper.entityToVO(pages.getRecords());
        ListResult<AuditOrganizationsVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(auditOrganizationsVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }


    /**
     * 新增或修改 内部机构管理
     */
    @PostMapping("/submit")
    @Resubmit(delaySeconds = 0)
    @LogOperation("内部机构管理-提交")
    public R submit(@Valid @RequestBody AuditOrganizations auditOrganizations) {
        if (!Optional.ofNullable(auditOrganizations.getId()).isPresent()) {
            auditOrganizations.setVersion("1");
        }
        if (!Optional.ofNullable(auditOrganizations.getStatus()).isPresent()) {
            auditOrganizations.setStatus(FormStatusConstant.UNREVIEWED);
        }

        if (auditOrganizations.getStatus() == FormStatusConstant.STASH){
            return auditOrganizationsService.saveOrUpdate(auditOrganizations) ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
        }

        if (!StringUtil.isEmpty(auditOrganizations.getCode()) || !StringUtil.isEmpty(auditOrganizations.getCompanyNameId())) {
            if (auditOrganizationsService.checkIsExisted(auditOrganizations.getId(), auditOrganizations.getCode(), auditOrganizations.getCompanyNameId())) {
                return auditOrganizationsService.saveOrUpdate(auditOrganizations) ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
            } else {
                return new R(MyCustomCode.BILL_ALREADY_EXISTS);
            }
        } else {
            return auditOrganizationsService.saveOrUpdate(auditOrganizations) ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
        }
    }


    /**
     * 删除 内部机构管理
     */
    @PostMapping("/remove")
    @LogOperation("内部机构管理-删除")
    public R remove(@RequestBody PageData pd) {
        List<String> ids = (List<String>)pd.get("ids");
        return auditOrganizationsService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA))) ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     * 变更 内部机构管理
     */
    @PostMapping("/change")
    @LogOperation("内部机构管理-变更")
    public R change(@Valid @RequestBody AuditOrganizations auditOrganizations) {
        if (StringUtil.isBlank(auditOrganizations.getCode())) {
            return new R(MyCustomCode.BILL_NOT_EMPTY);
        }
        if (!auditOrganizationsService.checkIsExisted(auditOrganizations.getId(), auditOrganizations.getCode(), auditOrganizations.getCompanyNameId())) {
            return new R(MyCustomCode.BILL_ALREADY_EXISTS2);
        }
        return auditOrganizationsService.change(auditOrganizations) ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

//    /**
//     * 企业内审机构基本情况表
//     */
//    @PostMapping("/auditAgencyBasic")
//    public ObjResult auditAgencyBasic(@Valid @RequestBody(required = false) AuditOrganizationsDTO auditOrganizationsDTO) {
//        ObjResult objResult;
//        try {
//            ReportReturnVO reportReturnVO = auditOrganizationsService.auditAgencyBasic(auditOrganizationsDTO);
//            objResult = new ObjResult(CommonCode.SUCCESS);
//            if (Optional.ofNullable(reportReturnVO).isPresent()) {
//                PageData pd = new PageData();
//                pd.put("grids", reportReturnVO.getGrids());
//                objResult.setPageData(pd);
//            }
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            objResult = new ObjResult(CommonCode.FAIL);
//        }
//        return objResult;
//
//    }
    /**
     * 生成excel文件
     * @param
     * @return
     */
    @GetMapping("/exportImportFile")
    @ApiOperation(value = "生成excel文件")
    public ObjResult export(){
        PageData pd = new PageData();
        pd.put("key", auditOrganizationsService.export());
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        objResult.setPageData(pd);
        return objResult;
    }

    /**
     * 下载excel文件 并删除
     *
     * @param key
     * @param response
     */
    @GetMapping("/download/{key}")
//    @PassToken
    public void download(@PathVariable String key, HttpServletResponse response) {
        auditOrganizationsService.download(key, response);
    }
}
